package com.ricky.serviceuser.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ricky.common_util.helper.JwtHelper;
import com.ricky.common_util.result.ResultCodeEnum;
import com.ricky.hosp.enums.AuthStatusEnum;
import com.ricky.hosp.model.acl.User;
import com.ricky.hosp.model.user.Patient;
import com.ricky.hosp.model.user.UserInfo;
import com.ricky.hosp.vo.user.LoginVo;
import com.ricky.hosp.vo.user.UserAuthVo;
import com.ricky.hosp.vo.user.UserInfoQueryVo;
import com.ricky.service_util.common.exception.ReservationException;
import com.ricky.serviceuser.mapper.UserInfoMapper;
import com.ricky.serviceuser.service.PatientService;
import com.ricky.serviceuser.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //从vo中获取手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //判断登录信息是否为空，采用spring-boot-starter-validation控制
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)){
            throw new ReservationException(ResultCodeEnum.PARAM_ERROR);
        }
        //判断验证码是否一致
        String redisCode = redisTemplate.opsForValue().get(phone);
        if(!code.equals(redisCode)){
            throw new ReservationException(ResultCodeEnum.CODE_ERROR);
        }
        //绑定手机号码，根据请求是否包含openid判断该用户是否以微信方式进行登录
        UserInfo userInfo = null;
        if(!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = this.selectWxInfoOpenId(loginVo.getOpenid());
            if(null != userInfo) {
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            } else {
                throw new ReservationException(ResultCodeEnum.DATA_ERROR);
            }
        }
        // 如果userInfo为空，进行正常的手机登录
        if (userInfo == null){
            //判断用户是否是第一次登录，查询数据库中是否存在相同的手机号
            QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
            userInfoQueryWrapper.eq("phone",phone);
            userInfo = baseMapper.selectOne(userInfoQueryWrapper);
            if (userInfo == null){
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        }

        //校验用户是否被禁用
        if (userInfo.getStatus() == 0){
            throw new ReservationException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //不是第一次则直接登录
        //返回登录信息
        //返回用户名
        //返回Token
        HashMap<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)){
            name = userInfo.getPhone();
        }
        map.put("name",name);
        // jwt生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);
        return map;
    }

    @Override
    public UserInfo selectWxInfoOpenId(String openid) {
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("openid",openid);
        UserInfo userInfo = baseMapper.selectOne(userInfoQueryWrapper);
        return userInfo;
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        // 根据用户id查询出用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证信息
        //认证人姓名
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //进行信息更新
        baseMapper.updateById(userInfo);
    }

    //用户列表条件查询带分页
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        // 通过userInfoQueryVo获取条件值
        String name = userInfoQueryVo.getKeyword();//用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();//认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();//开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();//结束时间
        //对条件值进行非空判断
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)){
            userInfoQueryWrapper.like("name",name);
        }
        if (!StringUtils.isEmpty(status)){
            userInfoQueryWrapper.eq("status",status);
        }
        if (!StringUtils.isEmpty(authStatus)){
            userInfoQueryWrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)){
            userInfoQueryWrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)){
            userInfoQueryWrapper.le("create_time",createTimeEnd);
        }
        //调用mapper方法实现分页查询
        Page<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, userInfoQueryWrapper);
        //编号变成对应值
        userInfoPage.getRecords().stream().forEach(this::packageUserInfo);
        return userInfoPage;
    }
    // 用户锁定
    @Override
    public void lock(Long userId, Integer status) {
        if (status==0||status==1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        this.packageUserInfo(userInfo);
        map.put("userInfo",userInfo);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllUserId(userId);
        map.put("patientList",patientList);
        return map;
    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        // 2通过，-1不通过
        if (authStatus ==2||authStatus==-1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    private void packageUserInfo(UserInfo userInfo){
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态
        String statusString = userInfo.getStatus() ==0?"锁定":"正常";
        userInfo.getParam().put("statusString",statusString);
    }
}
